<template>
  <div class="main">
    <!-- 查询表单 -->
    <el-form :inline="true" :model="searchMap" class="demo-form-inline showtable" ref="searchMap">
      <el-form-item prop="gname">
        <el-input v-model="searchMap.gname" placeholder="商品名字" style="width: 200px;"></el-input>
      </el-form-item>
      <el-form-item prop="typename">
        <el-input
          readonly
          @click.native="dialogTotalTypeVisible = true"
          v-model="searchMap.typename"
          placeholder="总商品类型请选择"
          style="width: 200px;"
        ></el-input>
      </el-form-item>
      <el-form-item prop="kname">
        <el-input
          readonly
          @click.native="dialogGoodsTypeVisible=true"
          v-model="searchMap.kname"
          placeholder="商品类型"
          style="width: 200px;"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
        <el-button @click="handleAdd" type="success">新增</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 表格显示 -->
    <el-table :data="tableData" style="width: 100%" max-height="460px" border stripe>
      <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
      <el-table-column prop="gname" label="商品名字" width="200" align="center"></el-table-column>
      <el-table-column
        prop="typeId"
        label="总商品类型"
        width="120"
        align="center"
        v-if="$store.state.goodstype.totaltype.length!=0"
      >
        <template slot-scope="scope">
          <span>{{scope.row.typeId | totalTypeFilter}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="kid"
        label="商品类型"
        width="120"
        align="center"
        v-if="$store.state.goodstype.goodtype.length!=0"
      >
        <template slot-scope="scope">
          <span>{{scope.row.kid | TypeFilter}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="gimg" label="商品图片路径" width="450" align="center"></el-table-column>
      <el-table-column prop="gprice" label="商品单价" width="100" align="center"></el-table-column>
      <el-table-column prop="gstock" label="商品库存" width="120" align="center"></el-table-column>
      <el-table-column label="操作" align="center" width="150">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页显示 -->
    <div class="fenye">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        hide-on-single-page
      ></el-pagination>
    </div>

    <!-- 对话框 -->
    <el-dialog :title="id?'编辑商品':'新增商品'" :visible.sync="dialogFormVisible" width="500px" top="10px">
      <el-form
        :model="pojo"
        ref="pojoFrom"
        label-width="100px"
        label-position="right"
        style="width: 400px;"
        status-icon
        :rules="rules"
      >
        <el-form-item prop="gname" label="商品名字">
          <el-input v-model="pojo.gname" placeholder="商品名字"></el-input>
        </el-form-item>
        <el-form-item prop="typename" label="总商品类型">
          <el-input
            readonly
            @click.native="dialogTotalTypeVisible = true"
            v-model="pojo.typename"
            placeholder="总商品类型请选择"
          ></el-input>
        </el-form-item>
        <el-form-item prop="kname" label="商品类型">
          <el-input
            readonly
            @click.native="dialogGoodsTypeVisible=true"
            v-model="pojo.kname"
            placeholder="商品类型"
            style="width: 200px;"
          ></el-input>
        </el-form-item>
        <el-form-item prop="gimg" label="商品图片路径">
          <el-input v-model="pojo.gimg" placeholder="商品图片路径"></el-input>
        </el-form-item>
        <el-form-item prop="gprice" label="商品单价">
          <el-input v-model="pojo.gprice" placeholder="商品单价"></el-input>
        </el-form-item>
        <el-form-item prop="gstock" label="商品库存">
          <el-input v-model="pojo.gstock" placeholder="商品库存"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="id?updataMember('pojoFrom'):addMember('pojoFrom')">确 定</el-button>
        <el-button @click="dialogFormVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 总商品类型弹窗 -->
    <el-dialog title="选择总商品类型" :visible.sync="dialogTotalTypeVisible" width="500px">
      <total-type :isshow="true" class="type" @option-totaltype="optionTotaltype"></total-type>
    </el-dialog>
    <!-- 商品类型弹窗 -->
    <el-dialog title="选择商品类型" :visible.sync="dialogGoodsTypeVisible" width="440px">
      <goods-type :isgoodsshow="true" @option-type="optiontype"></goods-type>
    </el-dialog>
  </div>
</template>

<script>
import goodsApi from "@/api/goods";
import store from "@/store";
import totalType from "@/views/totalType";
import goodsType from "@/views/goodsType";
export default {
  data() {
    return {
      tableData: [],
      currentPage: 1, //当前页
      pageSize: 5, //一页10条数据
      total: 100,
      searchMap: {
        //查询条件
        gname: "",
        typename: "",
        typeId: "",
        kid: "",
        kname: ""
      },
      oldDate: 0, //存旧时间
      newDate: 0, //当前时间(毫秒)
      pojo: {
        //新增会员数据
        gname: "",
        typeId: "",
        kid: "",
        kname: "",
        gimg: "",
        gprice: "",
        gstock: "",
        typename: ""
      },
      dialogFormVisible: false, //对话框的显示
      rules: {
        //新增会员验证
        gname: [{ required: true, message: "请输入商品名字", trigger: "blur" }],
        typeId: [
          { required: true, message: "请输入总商品类型", trigger: "blur" }
        ],
        kid: [{ required: true, message: "请输入商品类型", trigger: "blur" }],
        gimg: [{ required: true, message: "传入图片", trigger: "blur" }],
        gprice: [
          { required: true, message: "请输入商品单价", trigger: "blur" }
        ],
        gstock: [{ required: true, message: "请输入商品库存", trigger: "blur" }]
      },
      id: null,
      isEdit: false, //总商品类型开关
      isEdit2: false, //商品类型开关
      dialogTotalTypeVisible: false, //总类型弹窗
      dialogGoodsTypeVisible: false //商品类型弹窗
    };
  },

  components: {
    totalType,
    goodsType
  },

  methods: {
    //查询商品
    async searchGoods(searchMap) {
      try {
        let p = await goodsApi.getgoods(searchMap);
        // console.log(p);
        if (p.data.flag) {
          // console.log(p);
          if (p.data.data.length > this.pageSize) {
            let arr = [];
            for (let i = 0; i < this.pageSize; i++) {
              arr.push(p.data.data[i]);
            }
            this.tableData = arr;
          } else {
            this.tableData = p.data.data;
          }
          this.total = p.data.total;
          this.$message({
            message: "查询成功",
            type: "success"
          });
          // console.log(this.tableData);
        }
      } catch (err) {
        console.log(err);
      }
    },
    //点击查询
    onSubmit() {
      let istrue = this.clickToFast();
      if (istrue) {
        this.searchGoods(this.searchMap);
        // console.log("过了800毫秒了");
      } else {
        console.log("还没过800毫秒");
      }
    },
    //获取分页数据
    async getSearch() {
      try {
        //把要第几页、一页多少条一并发给后端
        let p = await goodsApi.searchgoods(this.currentPage, this.pageSize);
        if (p.data.flag) {
          this.tableData = p.data.data;
          this.total = p.data.total;
        }
      } catch (err) {
        console.log(err);
      }
    },
    //更换一页条数
    handleSizeChange(val) {
      //val  是当页面条数发生改变时 传入得新值  如  当页面初始条数是10 点击更换成20条 那val就是20
      this.pageSize = val;
      this.getSearch();
    },
    //更换当前页码
    handleCurrentChange(val) {
      //val 当点击更换当前页时  val就是要更换得页码数
      this.currentPage = val;
      this.getSearch();
    },
    //删除商品
    handleDelete(row) {
      console.log(row);
      this.$confirm("确定要删除该商品吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.deleteUser(row.gid);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //删除商品，请求ajax
    async deleteUser(id) {
      try {
        let p = await goodsApi.delgoods(id);
        if (p.data.flag) {
          this.$message({
            type: "success",
            message: "删除成功!"
          });
          this.getSearch();
        } else {
          this.$message({
            type: "erroe",
            message: "删除失败!"
          });
        }
      } catch (err) {
        console.log("ajax请求失败", err);
      }
    },
    //对话框显示t
    handleAdd() {
      this.id = null;
      this.isEdit = true;
      this.isEdit2 = true;
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        //this.$nextTick() 它是一个异步事件，当渲染结束 之后，它的回调函数才被执行
        this.pojo = {
          //新增会员数据
          gname: "",
          typeId: "",
          kid: "",
          kname: "",
          gimg: "",
          gprice: "",
          gstock: "",
          typename: ""
        };
        this.$refs["pojoFrom"].resetFields();
      });
    },
    //新增信息
    addMember(pojoFrom) {
      this.$refs[pojoFrom].validate(valid => {
        if (valid) {
          //表单正则验证通过 发送ajax
          this.addUser(this.pojo);
        } else {
          //正则验证不通过
          this.$message({
            message: "请把必填的填写完整",
            type: "error"
          });
        }
      });
    },
    //添加一个新商品 发送ajax
    async addUser(pojo) {
      try {
        let p = await goodsApi.addgoods(pojo);
        if (p.data.flag) {
          //新增成功
          this.$message({
            message: "添加成功",
            type: "success"
          });
          this.dialogFormVisible = false;
        } else {
          //新增失败
          this.$message({
            message: "添加失败",
            type: "error"
          });
        }
      } catch (err) {
        //ajax 报错
        console.log("发送ajax失败", err);
      }
    },
    //防止点击过快
    clickToFast() {
      this.oldDate = this.newDate;
      this.newDate = new Date().getTime();
      if (this.newDate - this.oldDate > 800) {
        return true;
      } else {
        return false;
      }
    },
    //修改信息
    handleEdit(row) {
      this.dialogFormVisible = true;
      this.id = row.gid;
      this.isEdit = true;
      this.isEdit2 = true;
      for (let key in this.pojo) {
        this.pojo[key] = row[key];
      }
      for (let key in this.$store.state.goodstype.totaltype) {
        if (
          this.pojo.typeId == this.$store.state.goodstype.totaltype[key].type
        ) {
          this.pojo.typename = this.$store.state.goodstype.totaltype[key].name;
        }
      }
      for (let key in this.$store.state.goodstype.goodtype) {
        if (this.pojo.kid == this.$store.state.goodstype.goodtype[key].type) {
          this.pojo.kname = this.$store.state.goodstype.goodtype[key].gname;
        }
      }
    },
    //更新商品
    updataMember(pojoFrom) {
      this.$refs[pojoFrom].validate(vaild => {
        if (vaild) {
          this.updataUser(this.id, this.pojo);
        } else {
          this.$message({
            message: "亲，您还没填完噢",
            type: "error"
          });
        }
      });
    },
    //请求ajax 更新商品
    async updataUser(id, pojo) {
      try {
        let p = await goodsApi.updatatype(id, pojo);
        if (p.data.flag) {
          this.$message({
            message: "修改成功",
            type: "success"
          });
          this.dialogFormVisible = false;
          this.tableData.forEach(item => {
            if (item.gid == id) {
              for (let key in pojo) {
                item[key] = pojo[key];
              }
            }
          });
        } else {
          this.$message({
            message: "修改失败",
            type: "error"
          });
        }
      } catch (err) {
        console.log("ajax请求出错", err);
      }
    },
    //接收总商品类型 传来得数据
    optionTotaltype(currentRow) {
      this.dialogTotalTypeVisible = false;
      if (this.isEdit) {
        this.pojo.typename = currentRow.type;
        this.pojo.typeId = currentRow.typeId;
      } else {
        this.searchMap.typename = currentRow.type;
        this.searchMap.typeId = currentRow.typeId;
      }
      this.isEdit = false;
    },
    //接收总商品类型 传来得数据
    optiontype(currentRow) {
      // console.log(currentRow);
      this.dialogGoodsTypeVisible = false;
      if (this.isEdit2) {
        this.pojo.kname = currentRow.kname;
        this.pojo.kid = currentRow.kid;
      } else {
        this.searchMap.kname = currentRow.kname;
        this.searchMap.kid = currentRow.kid;
      }
      this.isEdit2 = false;
    },
    //重置
    reset() {
      this.$refs["searchMap"].resetFields();
      this.searchMap.typeId = "";
      this.searchMap.kid = "";
    }
  },
  created() {
    this.getSearch();
    this.$store.dispatch("getTotalType");
    this.$store.dispatch("getType");
  },
  filters: {
    //过滤器
    totalTypeFilter(type) {
      return store.state.goodstype.totaltype.filter(
        item => item.type == type
      )[0].name;
    },
    TypeFilter(type) {
      // console.log(type);
      if (type) {
        // console.log(type);
        return store.state.goodstype.goodtype.filter(
          item => item.type == type
        )[0].gname;
      }
    }
  }
};
</script>

<style scoped lang="scss">
.main {
  height: 80%;
}
</style>